<template>
	<div>
		<el-button @click="axiosData" type="primary">axios</el-button>
		<el-button @click="xhrData" type="success">xhr</el-button>
		<el-button @click="fetchData" type="success">fetch</el-button>
		<circular-loading :immediate="immediate" :percentage="percentage" :speed="speed">
			<!-- 这里可以放置需要在加载时被遮罩的内容 -->
		</circular-loading>
	</div>
</template>

<script setup lang="ts">
import axios from "axios"
import circularLoading from "./child.vue"
const percentage = ref(0)
const immediate = ref(false)
const speed = ref(0)
let startTime = 0
let loaded = 0
async function axiosData() {
	immediate.value = true
	percentage.value = 0
	startTime = Date.now()
	loaded = 0
	try {
		await axios
			.get("/api/query", {
				onDownloadProgress: (progressEvent) => {
					const total = progressEvent.total
					const current = progressEvent.loaded
					const currentTime = Date.now()
					const timeElapsed = (currentTime - startTime) / 1000 // 转换为秒
					const currentSpeed = (current - loaded) / timeElapsed / 1024 // 转换为 KB/s
					speed.value = Math.round(currentSpeed)
					percentage.value = Math.round((current / total) * 100)
					loaded = current
					startTime = currentTime
					console.log(`${percentage.value}%`, progressEvent)
				},
			})
			.then((response) => {
				console.log(response.data)
				immediate.value = false
			})
	} catch (error) {
		console.error("请求失败:", error)
		alert("获取数据时发生错误，请稍后再试。")
	}
}
async function xhrData() {
	immediate.value = true
	percentage.value = 0
	try {
		const xhr = new XMLHttpRequest()
		xhr.open("GET", "/api/query")
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4 && xhr.status === 200) {
				immediate.value = false
				const data = xhr.responseText
				const jsonData = JSON.parse(data)
				console.log(jsonData)
			}
		}
		xhr.addEventListener("progress", (e) => {
			const { loaded, total } = e
			console.log(parseInt((loaded / total) * 100, 0) + "%")
			percentage.value = parseInt((loaded / total) * 100, 0)
		})
		xhr.send()
	} catch (error) {
		console.error("请求失败:", error)
		alert("获取数据时发生错误，请稍后再试。")
	}
}
async function fetchData() {
	immediate.value = true
	percentage.value = 0
	try {
		fetch("/api/query").then(async (res) => {
			if (!res || !res.body) {
				return
			}
			const contentLength = res.headers.get("content-length")
			let total = contentLength ? parseInt(contentLength, 10) : 0
			let loaded = 0
			const reader = res.body.getReader()
			let chunks = []
			while (true) {
				const { done, value } = await reader.read()
				if (done) {
					break
				}
				// 将每次读取的数据块追加到 chunks 数组中
				chunks.push(value)
				loaded += value.length
				percentage.value = parseInt((loaded / total) * 100, 0)
				console.log(parseInt((loaded / total) * 100, 0))
			}
			// 将所有数据块合并成一个 Blob 对象
			const blob = new Blob(chunks, { type: "application/json" })

			// 将 Blob 转换为 JSON 字符串
			const text = await new Response(blob).text()

			// 解析 JSON 字符串
			const data = JSON.parse(text)
			immediate.value = false
			console.log(data) // 打印最终的 JSON 数据
		})
	} catch (error) {
		console.error("请求失败:", error)
		alert("获取数据时发生错误，请稍后再试。")
	}
}
</script>

<style lang="scss" scoped></style>
